#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "ChenRenJian"
# Date: 2019/1/18

# coding:utf-8
from ctypes import *
import requests
import json
import random
import binascii
import os


class Chaoren():
    def __init__(self):
        self.s = requests.Session()
        self.s.encoding = 'utf-8'
        self.data = {
            'username': '',
            'password': '',
            'softid': '3696',  # 修改为自己的软件id
            'imgid': '',
            'imgdata': ''
        }

    def get_left_point(self):
        try:
            r = self.s.post('http://api2.sz789.net:88/GetUserInfo.ashx', self.data)
            return r.json()
        except requests.ConnectionError:
            return self.get_left_point()
        except:
            return False

    def recv_byte(self, imgdata):
        self.data['imgdata'] = binascii.b2a_hex(imgdata).upper()
        try:
            r = self.s.post('http://api2.sz789.net:88/RecvByte.ashx', self.data)
            res = r.json()
            if res[u'info'] == -1:
                return False
            return r.json()
        except requests.ConnectionError:
            return self.recv_byte(imgdata)
        except:
            return False

    def report_err(self, imgid):
        self.data['imgid'] = imgid
        if self.data['imgdata']:
            del self.data['imgdata']
        try:
            r = self.s.post('http://api2.sz789.net:88/ReportError.ashx', self.data)
            return r.json()
        except requests.ConnectionError:
            return self.report_err(imgid)
        except:
            return False


def image_main(imgdata):
    client = Chaoren()
    client.data['username'] = '15705915967'  # 修改为打码账号
    client.data['password'] = 'iamdeng'  # 修改为打码密码
    # 提交识别
    # imgpath = os.path.join(os.path.dirname(__file__), 'img.jpg')
    # imgdata = open('https://login.sina.com.cn/cgi/pin.php?p=yf-70b3300877a80dd03dfb38655d134ed9cc58', 'rb').read()
    res = client.recv_byte(imgdata)
    print(res[u'result'])  # 识别结果

    return res[u'result']


# test
if __name__ == '__main__':
    imgpath ='D:/wj/test/weibo_spidre3/captcha.jpeg'
    imgdata = open(imgpath, 'rb').read()
    image_main(imgdata)

    # from skimage import io
    #
    # image = io.imread('https://login.sina.com.cn/cgi/pin.php?p=yf-70b3300877a80dd03dfb38655d134ed9cc58')
    # io.imshow(image)
    # io.show()



